﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetNote.Repository;
using NetNote.ViewModels;

namespace NetNote.Api
{
    [Route("api/[controller]")]
    [ApiController]
    public class NoteController : Controller
    {
        private INoteRepository _noteRepository;
        private INoteTypeRepository _noteTypeRepository;
        public NoteController(INoteRepository noteRepository, INoteTypeRepository noteTypeRepository)
        {
            _noteRepository = noteRepository;
            _noteTypeRepository = noteTypeRepository;
        }

        [HttpGet("{pageIndex}")]
        public IActionResult Get(int pageIndex = 1)
        {
            var pageSize = 10;
            var notes = _noteRepository.PageList(pageIndex, pageSize);
            ViewBag.PageCount = notes.Item1;
            ViewBag.PageIndex = notes.Item2;
            var result = notes.Item1.Select(s => new NoteViewModel
            {
                Attachment = s.Attachment,
                Content = s.Content,
                Id = s.Id,
                Title = s.Title,
                Type = s.Type.Name
            });
            return Ok(result);
        }
        [HttpGet("{id}/{password}")]
        public async Task<IActionResult> Detail(int id, string password)
        {
            var note = await _noteRepository.GetByidAsync(id);
            if (note == null)
            {
                return NotFound();
            }
            if (!string.IsNullOrEmpty(note.Password) && !note.Password.Equals(password))
            {
                return Unauthorized();
            }
            var result = new NoteViewModel() { Id = note.Id, Attachment = note.Attachment, Content = note.Content, Title = note.Title, Type = note.Type.Name };
            return Ok(result);
        }
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] NoteModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            string filename = string.Empty;
            await _noteRepository.AddAsync(new Models.Note() { Content= model .Content, Create= model .Create, Id= model .Id, Password= model .Password, Title= model .Title, TypeId= model .Type});
            return CreatedAtAction("index","");
        }
    }
}